Explain with example the RegExp Object in javascript
Explain with example the RegExp Object in javascript
314
14-Feb-2025
Updated on 14-Feb-2025
Amrith Chandran
14-Feb-2025Regular expression (
RegExp) is a sequence of characters that forms a search pattern. It is used for pattern matching and string manipulation in JavaScript.Creating a
RegExpObjectThere are two ways to create a regular expression are given as below,
RegExpConstructorDifference:
Constructors allow dynamic pattern creation, while literal notation is simpler and more commonly used.
RegExp Methods
there are several RegExp methods to match a pattern in a given variable values,
test()- Checks if a pattern existsReturns
trueorfalsedepending on whether the pattern is found or not.match()- Finds matches in a stringReturns an array of matches, or return
nullif no matches are found.replace()- Replaces matched textIt replaces a specific pattern match in given values
search()- Returns the index of the first matchIt matches a pattern in a given value or we can say that it search a specific pattern in the given value and returns the index number if found.
split()- Splits a string using a regex patternRegExp Flags (Modifiers)
Flags modify the way the regular expression works.
g: Global match (find all matches)i: Case-insensitive matchm: Multi-line matchExample:
RegExp Special Characters & Metacharacters
\d: Matches a digit (0-9)\D: Matches a non-digit\w: Matches an alphanumeric character (A-Z, a-z, 0-9, _)\W: Matches a non-word character\s: Matches whitespace\S: Matches non-whitespace^: Matches the start of a string$: Matches the end of a string.*: Matches any character(s)Example:
I hope you understand clearly the RegExp object in javascrip.
Thanks.
Also, read: Explain the Date object in javascript.